package com.guodi.map.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.DateUtil;
import com.guodi.common.utils.SoeUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.tool.api.R;
import com.guodi.map.utils.ShapeReaderUtil;
import com.guodi.map.vo.ShapeModelVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.csource.common.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @描述: 工具服务控制类
* @作者: 代鹏刚
* @日期: 2019/8/13 18:41
**/
@Api(value = "API - ShaManagerController",
        tags = "工具服务")
@RestController
@RequestMapping("/ShaManager")
public class ShaManagerController extends BaseController {

    // CAD、txt文件导入SOE路径
    @Value("${map.impCadUrl}")
    private String impCadUrl ;


    /**
    * @描述:  加载本地shp图层
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2019/8/26 11:07
    **/
    @ApiOperation("数据叠加-加载本地图层")
    @PostMapping({"/reloadShapeFile"})
    @ApiParam(name = "file",value = "file", required = true)
    public R<ArrayList<ShapeModelVO>> reloadShapeFile(@RequestParam(value = "file") MultipartFile file){
        String fileName = file.getOriginalFilename();
        String fileFormat = fileName.substring(fileName.lastIndexOf(".") + 1);
        if(!fileFormat.equals("shp")){
            return R.fail(StatusCode.ERROR_CODE_40005,"请上传shp格式的文件!!");
        }
        String entityId = "temp_"+ DateUtil.getTime();
        Map<String, Object> fileMap = new HashMap<>();
        String realPath = "";
        /*Map<String, Object> fileMap = sysFileService.uploadAndSave("Chase", file,
                "AP_DOC", entityId,null, "Chase");*/
        //String realPath = sysFileService.getUploadDirPath().replace("upload","")+fileMap.get("filePath").toString(); --新基础运维
        ShapeReaderUtil shapeReader = new ShapeReaderUtil();
        //删除上次存放的shape文件
        String folderPath = realPath.substring(0,realPath.lastIndexOf("/"));
        File folder = new File(folderPath);
        if (folder != null && folder.exists()){
            deleteFile(folder,fileMap.get("fileId").toString());
        }
        ArrayList<ShapeModelVO> shapeModelVOS = shapeReader.readShapeFile(realPath);
        return R.data(shapeModelVOS);

    }

    /**
    * @描述: 加载cad文件
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2021/4/12 14:39
    **/
    @RequestMapping(value = "/loadCadFile", produces = "application/json;charset=utf-8")
    @SuppressWarnings("static-access")
    public R loadCadFile(MultipartHttpServletRequest multipartRequest, HttpServletRequest request, HttpServletResponse response) {
        List<String> resultList = new ArrayList<String>();
        try {
            List<MultipartFile> files = multipartRequest.getFiles("file");
            Map<String, String> param = new HashMap<String, String>();
            param.put("f", "json");
            Base64 encoder = new Base64();
            for (MultipartFile multipartFile : files) {
                if (multipartFile.getOriginalFilename().toLowerCase().indexOf(".dxf") != -1) {
                    param.put("fileStream", encoder.encode(multipartFile.getBytes()));
                    param.put("ext", "dxf");
                }
                if (multipartFile.getOriginalFilename().toLowerCase().indexOf(".dwg") != -1) {
                    param.put("fileStream", encoder.encode(multipartFile.getBytes()));
                    param.put("ext", "dwg");
                }
                resultList.add(SoeUtil.callRestSoeService(this.impCadUrl, param));
                // resultList.add(SoeUtils.callRestSoeService("impCad.url", param));
            }
            /**设置响应头允许ajax跨域访问**/
            response.setHeader("Access-Control-fcAllow-Origin", "*");
            /*星号表示所有的异域请求都可以接受，*/
            response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        } catch (Exception e) {
            e.printStackTrace();
            R.fail("加载失败");
        }
        return R.data(resultList);
    }

    public void deleteFile(File folder, String fileName){
        File[] files = folder.listFiles();
        //遍历该目录下的文件对象
        for (File f: files){
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()){
                deleteFile(f,fileName);
            }else {
                if(f.getName().indexOf(fileName) == -1){
                    f.delete();
                }
            }
        }
    }

    /**
    * @描述: 利用高德地图检索地名
    * @入参:
    * @出参:  lng,lat
    * @作者: 代鹏刚
    * @日期: 2019/9/23 9:43
    **/
    @ApiOperation("通过地址地名检索地图定位")
    @PostMapping({"/mapLocation"})
    @ApiImplicitParam(name = "addr",value = "地址",dataType = "string", required = true)
    public R getCoordinate(String addr) {
        String lng = null;
        String lat = null;
        String url = "http://restapi.amap.com/v3/geocode/geo?key=d2c64ae6d10d86763710e6345afae86a&address=" + addr;
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStreamReader insr = null;
        BufferedReader br = null;
        try {
            httpsConn = myURL.openConnection();
            if (httpsConn != null) {
                insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                String data = null;
                while((data= br.readLine())!=null){
                    JSONObject json = JSONObject.parseObject(data);
                    JSONArray jsonArray = json.getJSONArray("geocodes");
                    JSONObject obj = (JSONObject) jsonArray.get(0);
                    String coordinate =obj.get("location").toString();
                    String[] str = coordinate.split(",");
                    lng = str[0];
                    lat = str[1];
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(insr!=null){
                try {
                    insr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return R.data(new String[]{lng,lat});
    }
}
